package smtp;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Provider;
import javax.mail.Session;


import com.sun.mail.util.MailSSLSocketFactory;

/**
 * 
 * @author chandlerr, liw, wendlandts
 *
 */
public class SessionProperties extends Properties{
	private String user;
	private String pass;

	/**
	 * Optionally specify a file from which to load properties
	 * @param file - null if there is no properties file to load
	 */
	
	public SessionProperties(){
		
	}

	public Session getSession(String user, String pass){
		this.user = user;
		this.pass = pass;
		this.setProperty("user", user);
		this.setProperty("pass", pass);
		
		Session session = Session.getDefaultInstance(this);
		
		//protocol=imap; type=store; class=com.sun.mail.imap.IMAPStore; vendor=Sun Microsystems, Inc.;
		Provider store = new Provider (Provider.Type.STORE, "imap", "com.sun.mail.imap.IMAPStore", "Sun Microsystems, Inc.", null);
		
		//protocol=imap; type=store; class=com.sun.mail.imap.IMAPStore; vendor=Sun Microsystems, Inc.;
		Provider sstore = new Provider (Provider.Type.STORE, "imaps", "com.sun.mail.imap.IMAPSStore", "Sun Microsystems, Inc.", null);
		
		//protocol=smtp; type=transport; class=com.sun.mail.smtp.SMTPTransport; vendor=Sun Microsystems, Inc.;
		Provider transport = new Provider (Provider.Type.TRANSPORT, "smtp", "com.sun.mail.smtp.SMTPTransport", "Sun Microsystems, Inc.", null);
		
		session.addProvider(store);
		session.addProvider(sstore);
		session.addProvider(transport);
		return Session.getInstance(this, new EmailAuthenticator());

		
	}

	public void addIMAPProps(String host, int port){
		this.put("mail.imap.host", host);
		this.put("mail.imap.port", port);
		this.put("mail.imap.socketFactory.port", port);
	}
	
	public void addIMAPSProps(String host, int port){
		this.put("mail.imaps.host", host);
		this.put("mail.imaps.port", port);
		this.put("mail.imaps.socketFactory", MailSSLSocketFactory.class);
		this.put("mail.imaps.socketFactory.fallback", false);
		this.put("mail.imaps.ssl.socketFactory.port", port);
		this.put("mail.imaps.ssl.trust", "*");
		this.put("mail.imap.ssl.protocols", "imaps");
	}

	public void addSMTPProps (String host,int port){		
		this.put("mail.smtp.host", host);
		this.put("mail.smtp.port", port);
		this.put("mail.smtp.auth", "true");

	}

	private class EmailAuthenticator extends Authenticator{

		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(user, pass);
			
		}
	}


}
